package com.key.modules.shiro;


/**
 * @Author：朕
 * @Package：com.key.modules.shiro
 * @Project：logistics_system
 * @name：ShiroConfig
 * @Date：2023/3/25 14:08
 * @Filename：ShiroConfig
 */

import com.key.modules.cache.RedisCacheManager;

import com.key.modules.shiro.global.AuthRealm;
import com.key.modules.shiro.propertes.ShiroProjectProperties;
import net.sf.ehcache.CacheManager;
import org.apache.shiro.cache.ehcache.EhCacheManager;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.LifecycleBeanPostProcessor;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;

import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

import javax.servlet.Filter;
import java.util.HashMap;
import java.util.LinkedHashMap;

/**
 * Shiro配置
 */
@Configuration
public class ShiroConfig {
    @Bean("securityManager")
    public SecurityManager securityManager(AuthRealm authRealm, RedisCacheManager redisCacheManager, DefaultWebSessionManager sessionManager) {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        //设置Reaml
        securityManager.setRealm(authRealm);
        //缓存设置到SecurityManager
        securityManager.setCacheManager(redisCacheManager);
        //设置session
        securityManager.setSessionManager(sessionManager);
        //记住我
        securityManager.setRememberMeManager(null);
        return securityManager;
    }

    @Bean("shiroFilter")
    public ShiroFilterFactoryBean shiroFilter(SecurityManager securityManager, ShiroProjectProperties properties) {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        /**
         * 添加自定义拦截器，重写user认证方式
         */
        HashMap<String, Filter> myFilters = new HashMap<>(16);
        myFilters.put("oauth2", new OAuth2Filter());
        shiroFilterFactoryBean.setFilters(myFilters);
        /**
         *  过滤规则（注意优先级）
         *  —anon 无需认证(登录)可访问
         * 	—authc 必须认证才可访问
         * 	—perms[标识] 拥有资源权限才可访问
         * 	—role 拥有角色权限才可访问
         * 	—user 认证和自动登录可访问
         */
        LinkedHashMap<String, String> filterMap = new LinkedHashMap<>();
        filterMap.put("/sulogin", "anon");
        String[] excludes = properties.getExcludes().split(",");
        for (String exclude : excludes) {
            if (!StringUtils.isEmpty(exclude.trim())) {
                filterMap.put(exclude, "anon");
            }
        }
        filterMap.put("/**", "oauth2");//自定义过滤器：认证token
        // 设置过滤规则==不需要认证的接口、资源都放开,其他的都必须要认证或者有权限才能进来
        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterMap);
        // 设置登录页面
        shiroFilterFactoryBean.setLoginUrl("/sulogin");
        // 未授权错误页面
        //shiroFilterFactoryBean.setUnauthorizedUrl("/noAuth");
        return shiroFilterFactoryBean;
    }

    /**
     * 自定义的Realm
     */
    @Bean
    public AuthRealm getRealm(RedisCacheManager redisCacheManager) {
        AuthRealm authRealm = new AuthRealm();
        //开启全局缓存
        authRealm.setCachingEnabled(true);
        //设置缓存管理器
        authRealm.setCacheManager(redisCacheManager);
        //开启认证缓存
        authRealm.setAuthenticationCachingEnabled(true);
        //设置认证的缓存名称
        authRealm.setAuthenticationCacheName("authenticationCache");
        //开启授权缓存
        authRealm.setAuthorizationCachingEnabled(true);
        //设置授权缓存名称
        authRealm.setAuthorizationCacheName("authorizationCache");
        return authRealm;
    }

    /**
     * 缓存管理器-使用Redis实现缓存
     * @return
     */
    @Bean
    public RedisCacheManager redisCacheManager(){
        RedisCacheManager redisCacheManager = new RedisCacheManager();
        return redisCacheManager;
    }

    /**
     * session管理器
     */
    @Bean
    public DefaultWebSessionManager getDefaultWebSessionManager(ShiroProjectProperties properties) {
        DefaultWebSessionManager sessionManager = new DefaultWebSessionManager();
        sessionManager.setGlobalSessionTimeout(properties.getGlobalSessionTimeout() * 1000);
        sessionManager.setSessionValidationInterval(properties.getSessionValidationInterval() * 1000);
        sessionManager.setDeleteInvalidSessions(true);
        sessionManager.validateSessions();
        // 去掉登录页面地址栏jsessionid
        sessionManager.setSessionIdUrlRewritingEnabled(false);
        return sessionManager;
    }

    @Bean("lifecycleBeanPostProcessor")
    public LifecycleBeanPostProcessor lifecycleBeanPostProcessor() {
        return new LifecycleBeanPostProcessor();
    }

    /**
     * 设置基于类方式代理
     */
    @Bean
    public DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator(){
        DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator = new DefaultAdvisorAutoProxyCreator();
        advisorAutoProxyCreator.setProxyTargetClass(true);
        return advisorAutoProxyCreator;
    }

    /**
     * 启用shrio授权注解拦截方式，AOP式方法级权限检查
     */
    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager){
        AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
        authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
        return authorizationAttributeSourceAdvisor;
    }

}
